<template>
  <div
    v-if="people && people.length"
    class="mx-[25px] sm:m-[30px_14px] xl:m-[50px]"
  >
    <div
      class="flex items-baseline mb-[15px]  xl:mb-[20px] "
    >
      <h2 class="text-[18px] xl:text-[24px]">Cast</h2>
    </div>

    <div class="relative overflow-hidden">
      <button
        class="absolute top-0 bottom-12 z-10 w-[30px] text-center bg-black/50 transition-all duration-200 left-0 group-hover:bg-black/75 focus:bg-black/75 disabled:cursor-default disabled:opacity-0"
        aria-label="Previous"
        type="button"
        :disabled="!canScrollLeft"
        @click="scrollLeft"
      >
        <RiArrowLeftWideFill class="text-white" />
      </button>

      <div ref="carouselElement" class="overflow-hidden" @scroll="checkScrollability">
        <div class="flex gap-2 w-max px-[10]">
          <CreditsItem
            class="flex-1 w-40 md:w-60"
            v-for="person in people"
            :key="`credit-${person.id}`"
            :person="person"
          />
        </div>
      </div>

      <button
        class="absolute top-0 bottom-12 z-10 w-[30px] text-center bg-black/50 transition-all duration-200 right-0 group-hover:bg-black/75 focus:bg-black/75 disabled:cursor-default disabled:opacity-0"
        aria-label="Next"
        type="button"
        :disabled="!canScrollRight"
        @click="scrollRight"
      >
        <RiArrowRightWideFill class="text-white" />
      </button>
    </div>
  </div>
</template>
<script setup>
import CreditsItem from "./CreditsItem.vue";
import { ref,onMounted } from "vue";
import { RiArrowLeftWideFill, RiArrowRightWideFill } from "vue-icons-plus/ri";

const { people } = defineProps({
  people: {
    type: Array,
    required: true,
  },
});

const carouselElement = ref(null);
const canScrollLeft = ref(false);
const canScrollRight = ref(false);

const checkScrollability = () => {
  if (carouselElement.value) {
    const { scrollLeft, scrollWidth, clientWidth } = carouselElement.value;
    canScrollLeft.value = scrollLeft > 0;
    canScrollRight.value = scrollLeft + clientWidth < scrollWidth;
  }
};


onMounted(()=>{
  if(carouselElement.value){
    const {scrollWidth,clientWidth} = carouselElement.value;
    if(scrollWidth <= clientWidth){
      canScrollRight.value = false;
    }else{
      canScrollRight.value = true;
    }
  }
})

const scrollLeft = () => {
  carouselElement.value?.scrollBy({
    left: -window.innerWidth,
    behavior: "smooth",
  });
};

const scrollRight = () => {
  carouselElement.value?.scrollBy({
    left: window.innerWidth,
    behavior: "smooth",
  });
};
</script>
